<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <link href="${gPath}/styles/dpl-min.css" rel="stylesheet"/>
    <link href="${gPath}/styles/bui-min.css" rel="stylesheet"/>
    <link href="${gPath}/styles/main.css" rel="stylesheet"/>
</head>
<body>

<!--列表页-->
<div class="container">
    <form id="searchForm" class="form-panel">
        <ul class="panel-content">
            <li>
                <span>
                    <span class="span2">出库时间：</span>
                    <div class="bui-form-group span12" data-rules="{dateRange : true}">
                        <input name="start_time" data-tip="{text : '起始时间'}" class="input-small calendar calendar-time" type="text" style="width: 170px;">
                        <label>&nbsp;-&nbsp;</label>
                        <input name="end_time" data-tip="{text : '结束时间'}" class="input-small calendar calendar-time"  type="text" style="width: 170px;">
                    </div>
                </span>
                <span>
                    <label>快递单号：</label><input type="text" class="control-text" name="productOutput.express_num"/>
                </span>
                <span>
                    <button type="button" id="btnSearch" class="button button-primary">搜索</button>
                </span>
            </li>
        </ul>
    </form>
    <div class="search-grid-container">
        <div id="grid"></div>
    </div>
</div>

<!--新增页面-->
<div id="addDialog" style="display: none">
    <form id="addForm" class="form-horizontal">
        <div class="control-group">
            <label class="control-label">快递单号：</label>
            <div class="controls">
                <input class="input-normal control-text" type="text" name="productOutput.express_num" style="width: 600px"/>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">
                备注
            </label>
            <div class="controls" style="height: 100px;">
                <textarea name="productOutput.remark" style="width: 600px; height: 85%; resize: none;"></textarea>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">
                批量SN：<br>(英文逗号分隔)
            </label>
            <div class="controls" style="height: 250px;">
                <textarea name="sns" data-rules="{required:true}" style="width: 600px; height: 100%; resize: none;"></textarea>
            </div>
        </div>
        <div class="row form-actions actions-bar">
            <div class="span13 offset3 ">
                <button type="submit" class="button button-primary">保存</button>
                <button type="reset" class="button">重置</button>
            </div>
        </div>
    </form>
</div>

<!-- 编辑页面 -->
<div id="editDialog" style="display: none">
    <form id="editForm" class="form-horizontal">
        <div class="control-group">
            <label class="control-label">快递单号：</label>
            <div class="controls">
                <input class="input-normal control-text" type="text" name="productOutput.express_num" style="width: 600px"/>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">
                备注
            </label>
            <div class="controls" style="height: 100px;">
                <textarea name="productOutput.remark" style="width: 600px; height: 85%; resize: none;"></textarea>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">
                SN：
            </label>
            <div class="controls" style="height: 250px;">
                <div>
                    <input id="sns" name="sns" type="hidden" value=""/>
                    <div hidefocus="true" tabindex="0" style="width: 620px;" class="bui-combox bui-select">
                        <div class="bui-simple-list">
                            <ul id="snUl"></ul>
                        </div>
                    </div>
                </div>
                <input type="text" placeholder="输入SN" onblur="addItem(this)" onkeydown="addItemWithKey(this,event)"/>
            </div>
        </div>
        <div class="row form-actions actions-bar">
            <div class="span13 offset3 ">
                <button type="submit" class="button button-primary">保存</button>
                <button type="reset" class="button">重置</button>
            </div>
        </div>
    </form>
</div>


<div id="importDialog" class="is-hide">
    <div class="text-center">
        <h1 class="pull-left span18">导入SN</h1>
        <p class="span18" style="margin-top: 5%">首先下载好EXCEL表格，再填写，再导入。 </p>
        <a target="_blank" href="http://7ktrix.com1.z0.glb.clouddn.com/clmp%E5%AF%BC%E5%85%A5%E8%AE%BE%E5%A4%87%E9%94%80%E5%94%AE%E8%AE%B0%E5%BD%95%E6%A8%A1%E6%9D%BF.xlsx" class="button">下载EXCEL表格模板</a>
        <hr>
    </div>
    <div class="text-center">
        <div id="J_Uploader"></div>
    </div>
    <div class="text-center importing" style="display: none;">
        <div class="tips tips-small tips-info span5 offset7">
            <span class="x-icon x-icon-small x-icon-info"><i class="icon icon-white icon-info"></i></span>
            <div class="tips-content">正在导入中，请稍后...</div>
        </div>
    </div>
</div>

<script type="text/javascript" src="${gPath}/scripts/jquery/jquery-1.8.1.min.js"></script>
<script type="text/javascript" src="${gPath}/scripts/bui.js"></script>
<script type="text/javascript" src="${gPath}/scripts/common/search.js"></script>
<script type="text/javascript">
    var URI = "${gPath}/clmp/dingtalk/pc/productOutput",MODULE='productOutput';
    BUI.use(['common/search', 'bui/uploader', 'bui/overlay', 'bui/form', 'bui/select', 'bui/editor'], function (Search, Uploader, Overlay, Form, Select, Editor) {
        var columns = [
            {dataIndex: 'id', visible: false},
            {dataIndex: 'operator_id', visible: false},
            {title: '出库人员', dataIndex: 'operator_name', width: '10%'},
            {title: '出库时间', dataIndex: 'output_time', width: '10%'},
            {title: '快递单号', dataIndex: 'express_num', width: '10%'},
            {title: '数量', dataIndex: 'count', width: '10%'},
            {title: '备注', dataIndex: 'remark', width: '59%'},
            {title: '操作', dataIndex: '', width: '10%', renderer: function (value, obj) {
                var editStr = '<shiro:hasPermission name="/clmp/dingtalk/pc/productOutput/*:post"><span class="grid-command btn-edit" title="编辑">编辑</span></shiro:hasPermission>';
                var delStr = '<shiro:hasPermission name="/clmp/dingtalk/pc/productOutput/*:delete"><span class="grid-command btn-del" title="删除">删除</span></shiro:hasPermission>';
                return editStr + delStr;
            }}
        ];
        var store = Search.createStore(URI, {totalProperty: 'total'});
        var gridCfg = Search.createGridCfg(columns, {
            tbar: {
                items: [
                    <shiro:hasPermission name="/clmp/dingtalk/pc/productOutput:post">
                    {
                        text: '<i class="icon-plus"></i>新增', btnCls: 'button button-small', handler: function () {
                        addForm.clearFields();
                        addForm.set('action', URI);
                        addForm.set('method', "POST");
                        addDialog.show();
                        }
                    },
                    </shiro:hasPermission>
                    {
                        <shiro:hasPermission name="/clmp/dingtalk/pc/productOutput/*:delete">
                        text: '<i class="icon-remove"></i>删除', btnCls: 'button button-small', handler: delFunction
                        </shiro:hasPermission>
                    }/*,
                    {
                        text: '<i class="icon-upload"></i>导入', btnCls: 'button button-small', handler: function () {
                            importDialog.show();
                        }
                    }*/
                ]
            },
            emptyDataTpl : '<div style="padding: 20px" class="centered"><img src="${gPath}/img/nodata.png"><h2>好像还没有数据</h2></div>',
            plugins: [BUI.Grid.Plugins.CheckSelection]
        });

        var search = new Search({
            store: store,
            gridCfg: gridCfg
        });
        var grid = search.get('grid');
        grid.on('cellclick', function (ev) {
            var sender = $(ev.domTarget); //点击的Dom
            if (sender.hasClass('btn-del')) {
                delItems([ev.record]);
            } else if (sender.hasClass('btn-edit')) {
                edit(ev.record);
            }
        });

        function delFunction() {
            var selections = grid.getSelection();
            delItems(selections);
        }

        function delItems(items) {
            var ids = [];
            BUI.each(items, function (item) {
                ids.push(item.id);
            });

            if (ids.length) {
                BUI.Message.Confirm('确认要删除选中的记录么？', function () {
                    $.ajax({
                        url: URI + "/" + ids.join("-"),
                        dataType: 'json',
                        type: 'DELETE',
                        data: {ids: ids},
                        success: function (data) {
                            if (data.status == 1) {
                                alert('操作成功');
                                search.load();
                            } else {
                                alert('删除失败！');
                            }
                        }
                    });
                }, 'question');
            }
        }

        function edit(record) {
            editForm.clearFields();
            editForm.set('action', URI + "/" + record.id);
            editForm.set('method', "POST");
            for (var name in record) {
                editForm.setFieldValue(MODULE +'.'+ name, record[name]);
            }
            loadSn(record);
            editDialog.show();
        }

        function loadSn(record){
            $.getJSON("${gPath}/clmp/productOutput/getSnByRecord", {recordId : record.id}, function(data){
                var snUl = $("#snUl");
                var snsArr = [];
                for (var i in data){
                    snUl.append('<li class="bui-list-item"><span>'+data[i].sn+'</span><button onclick="removeItem(this)">×</button></li>');
                    snsArr.push(data[i].sn);
                }
                $("#sns").val(snsArr.join());
            });
        }

        var importDialog = new Overlay.Dialog({
            title: '批量导入',
            width: 800,
            height: 400,
            mask: false,
            buttons: [],
            contentId: 'importDialog'
        });

        var editDialog = new Overlay.Dialog({
            title: '编辑',
            width: 800,
            height: 600,
            mask: false,
            buttons: [],
            contentId: 'editDialog'
        });
        editDialog.on("close hide", function(){
            $("#snUl").empty();
            $("#sns").val();
        });

        var addDialog = new Overlay.Dialog({
            title: '批量新增',
            width: 830,
            height: 600,
            mask: false,
            buttons: [],
            contentId: 'addDialog'
        });

        var addForm = new Form.HForm({
            srcNode: '#addForm',
            submitType: 'ajax',
            autoRender: true,
            callback: function (data) {
                if (data.status == 1) {
                    BUI.Message.Alert("操作成功<br/>"+ data.msg);
                    addDialog.hide();
                    search.load();
                } else {
                    BUI.Message.Alert("操作失败"+ data.msg);
                }
            }
        });

        var editForm = new Form.HForm({
            srcNode: '#editForm',
            submitType: 'ajax',
            autoRender: true,
            callback: function (data) {
                if (data.status == 1) {
                    BUI.Message.Alert("操作成功<br/>"+ data.msg);
                    editDialog.hide();
                    search.load();
                } else {
                    BUI.Message.Alert("操作失败"+ data.msg);
                }
            }
        });

        var uploader = new Uploader.Uploader({
            render: '#J_Uploader',
            url: '${gPath}/res/_webApi/excel/deviceSales',
            queue: {
                resultTpl:{
                    'success': '<div class="success">成功导入</div>',
                    'error': '<div class="error"><span class="uploader-error">{msg}</span></div>'
                }
            },
            rules: {
                //文的类型
                ext: ['.xls,.xlsx,.xlsm','文件类型只能为{0}'],
                //上传的最大个数
                max: [5, '文件的最大个数不能超过{0}个'],
                //文件大小的最小值,这个单位是kb
                minSize: [1, '文件的大小不能小于{0}KB'],
                //文件大小的最大值,单位也是kb
                maxSize: [1024, '文件大小不能大于1M']
            },
            isSuccess: function(result){
                $(".importing").hide();
                if(result && result.code == 20001){
                    BUI.Message.Alert("成功导入"+result.count+'条数据;<br>'+result.msg);
                    importDialog.hide();
                    search.load();
                    $(".action .bui-queue-item-del").click();
                    return true;
                }
                $(".action .bui-queue-item-del").click();
                BUI.Message.Alert("系统繁忙");
                return false;
            }
        }).render();

        uploader.on("start",function(e){
            $(".importing").show();
        });
    });

    function addItem(obj){
        var sn = obj.value.trim();
        if (sn != ""){
            if (!/^\d{9}$/.test(sn)){
                BUI.Message.Alert('sn必须是9位数字！');
                return;
            }
            var sns = $("#sns");
            var snsArr = sns.val().split(",");
            if (snsArr.indexOf(sn) == -1){
                $.getJSON("${gPath}/clmp/productOutput/checkSn", {sn: sn}, function(data){
                    if (data.status == 1){
                        $("#snUl").append('<li class="bui-list-item"><span>'+sn+'</span><button onclick="removeItem(this)">×</button></li>');
                        sns.val(sns.val() != "" ? sns.val() +","+ sn : sn);
                    } else {
                        BUI.Message.Alert(sn + data.msg);
                    }
                });
            }
        }
        obj.value = null;
    }

    function addItemWithKey(obj, e){
        if (e.keyCode == 13)
            $(obj).blur();
    }

    function removeItem(obj){
        var li = $(obj).parent("li");
        var sns = $("#sns");
        var tempIds = sns.val().split(",");
        tempIds.splice(tempIds.indexOf(li.contents().eq(0).text()), 1);
        sns.val(tempIds.length == 0 ? null : tempIds.join());
        li.remove();
    }
</script>
</body>
</html>